package com.examsystem.service.impl;


import com.examsystem.dao.AnswerMapper;
import com.examsystem.pojo.Answer;
import com.examsystem.pojo.vo.AnswerVo;
import com.examsystem.service.AnswerService;
import com.examsystem.pojo.vo.AnswerCards;
import com.examsystem.pojo.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

import static com.examsystem.Const.ConstMsg.*;


/**
 * @author cst
 */
@Service("answerServiceImpl")
@Slf4j
public class AnswerServiceImpl implements AnswerService {
    @Resource
    private AnswerMapper answerMapper;


    @Override
    public int addAnswer(Answer answer) {
        if (answer==null){
            throw new RuntimeException(GET_ANSWER_FAIL_MSG);
        }
        int addAnswer = answerMapper.addAnswer(answer);
        if (addAnswer==0){
            throw new RuntimeException(ADD_ANSWER_FAIL_MSG);
        }
        return addAnswer;

    }

    @Override
    public int addMulAnswer(List<Answer> answers) {
        if (answers==null||answers.size()!=0){
            throw new RuntimeException(GET_ANSWER_FAIL_MSG);
        }
        int addMulAnswer = answerMapper.addMulAnswer(answers);
        if (addMulAnswer==0){
            throw new RuntimeException(ADD_ANSWER_FAIL_MSG);
        }
        return addMulAnswer;
    }
    @Override
    public List<AnswerCards> queryAnswerCard(int userId, int paperId){
        List<AnswerCards> answerCards = answerMapper.queryAnswerCard(userId, paperId);
        if (answerCards==null||answerCards.isEmpty()){
            throw new RuntimeException(ADD_ANSWER_FAIL_MSG);
        }
        return answerCards;

    }

    /*
    教师端
     */

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThreadPoolTaskExecutor executor;

    /**
     * 【评分：教师手动给分、系统自动评分】
     * @param choice  选择 1：手改   2：自动改卷
     * @param point 给的分数
     * @param answerId 回答id
     * @param paperId 试卷id
     * @param questionId 试题id
     * @return result结果集对象
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public Result giveMark(Integer choice, Double point, Integer answerId, Integer paperId, int questionId, int classId) {
        //输入的分数匹配0+正整数
        String key = "giveMark: "+choice+answerId+paperId+classId+questionId+point;
            if (choice == NUMBER_1) {
                //手改
                if(answerMapper.givePoint(answerId, point) > 0) {
                    redisTemplate.opsForValue().set(key,point);
                    return Result.succ(true);
                }
            }else if (choice == NUMBER_2) {
                //自动改
                //获取所有的选择题的questionId
                List<Integer> questionIds = answerMapper.showPaperQuestionId(paperId);
                if (questionIds == null){
                    return Result.succ("没有选择题：null");
                }
                for (Integer id : questionIds) {
                    synchronized (this.getClass()){
                        //遍历出对于这道题的所有answerId
                        List<AnswerVo> answer = answerMapper.getAnswer2(paperId, id, classId);
                        for (AnswerVo answerVo : answer) {
                            int i = answerMapper.markAuto(answerVo.getAnswerId(), answerVo.getQuestionScore(), answerVo.getAnswerAnswer());
                            if (i > 0) {
                                redisTemplate.opsForValue().set(key, answerVo.getQuestionScore());
                            }
                        }
                    }
                    return Result.succ(true);
                }
            }
        return Result.succ(false);
    }



    /**
     * 显示学生的答案【用于填空】
     * @param paperId  试卷id
     * @param classId  班级id
     * @param questionId  试题id
     * @param begin 开始的下标【即，第一个开始的下标为0 ，每次点击begin都会+1，保证每次返回的都是一条学生关于这个问题的答案】
     * @return result结果集对象
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public AnswerVo showStudentAnswer(int paperId, int classId,int questionId,int begin) {
        //加上synchronized避免并发问题
        // 先从缓存获取数据如果有则直接返回
        //             如果无则查询MySQL，并将数据设置到缓存中

//        String key = "studentAnswer: "+ paperId+classId+questionId+begin;
//        Object answerObj = redisTemplate.opsForValue().get(key);
//        AnswerVo answerObj = null;
//        if (answerObj == null) {
//            synchronized (this.getClass()) {
////                answerObj = redisTemplate.opsForValue().get(key);
//                if (answerObj == null) {
//                    AnswerVo answer = answerMapper.getAnswer(paperId, questionId, begin, classId);
////                    redisTemplate.opsForValue().set(key, answer);
//                    return answer;
//                }else {
//                    return answerObj;
//                }
//            }
//        }
//        return answerObj;
        return answerMapper.getAnswer(paperId,questionId,begin,classId);
    }
}
